package config

import (
	"flag"
	"fmt"
	"github.com/spf13/viper"
	"go-chain-data/config/setting"
	"go-chain-data/global"
	"log"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"time"
)

type Config struct {
	vp *viper.Viper
}

func NewConfig() (*Config, error) {
	// 获取可执行文件的绝对路径
	exec, err := filepath.Abs(filepath.Dir(os.Args[0]))
	if err != nil {
		log.Fatal(err)
	}
	// 基于可执行文件的路径构建配置文件的绝对路径
	configPath := filepath.Join(exec, "config", "config.yaml")
	viper.SetConfigFile(configPath)
	vp := viper.New()
	vp.SetConfigName("config")
	vp.AddConfigPath("config")
	vp.SetConfigType("yaml")
	err = vp.ReadInConfig()
	if err != nil {
		return nil, err
	}
	return &Config{vp}, nil
}

func (config *Config) ReadSection(k string, v interface{}) error {
	err := config.vp.UnmarshalKey(k, v)
	if err != nil {
		return err
	}
	return nil
}

func SetupConfig() {
	conf, err := NewConfig()
	if err != nil {
		log.Panic("NewConfig error : ", err)
	}
	err = conf.ReadSection("Database", &global.DbConfig)
	if err != nil {
		log.Panic("ReadSection - Database error : ", err)
	}
	//err = conf.ReadSection("BlockChain", &global.BlockChainConfig)
	//if err != nil {
	//	log.Panic("ReadSection - BlockChain error : ", err)
	//}
	err = conf.ReadSection("Email", &global.EmailConfig)
	if err != nil {
		log.Panic("ReadSection - Email error : ", err)
	}
	err = conf.ReadSection("SettingBlockNumber", &global.BlockNumberConfig)
	if err != nil {
		log.Panic("ReadSection - BlockNumber error : ", err)
	}
}
func SetupDBEngine() {
	var err error
	global.DBEngine, err = NewDBEngine(global.DbConfig)
	if err != nil {
		log.Panic("NewDBEngine error : ", err)
	}
}

func SetupEthClient() {
	var err error
	global.EthRpcClient, err = NewEthRpcClient()
	if err != nil {
		log.Println("NewEthRpcClient error : ", err)
		time.Sleep(time.Second * 1)
		SetupEthClient()
	}
}

func SetupParams() {
	rpc := flag.String("rpc", "", "rpc")
	chainName := flag.String("name", "", "链名称")
	chainId := flag.String("id", "", "链ID")
	types := flag.String("type", "", "类型")
	diffNum := flag.String("diff", "", "区块间隔")
	flag.Parse()

	if *rpc == "" || *chainName == "" || *chainId == "" || *types == "" || *diffNum == "" {
		fmt.Println("请提供环境变量值 -rpc rpc地址 -name 链名称 -id 链ID -type 类型 -diff 区块间隔")
		return
	} else {
		// 字符串转int64
		id, err := strconv.ParseInt(*chainId, 10, 64)
		if err != nil {
			fmt.Printf("id不是正整数：%v", err)
			return
		}

		diff, err := strconv.ParseInt(*diffNum, 10, 64)
		if err != nil {
			fmt.Printf("diff不是正整数：%v", err)
			return
		}

		global.BlockChainConfig = &setting.BlockChainConfig{
			RpcUrl: *rpc,
			Name:   strings.ToUpper(*chainName),
			Id:     id,
			Type:   strings.ToUpper(*types),
			Diff:   diff,
		}
	}
}
